<template>
    <div id="roleManage" class="center_div">
        <div class="searchForm searchFormDataManageBtn22px" style="margin-top: 1%;margin-left: 1%;">
            <el-form :inline="true"  class="demo-form-inline">
                <el-form-item label="角色">
                    <el-input v-model="name" ></el-input>

                </el-form-item>
                <el-form-item>
                    <el-button type="primary"  @click="querySearch"class="dataManageBtn22BtnpPx">查询</el-button>
                    <el-button type="primary"  @click="add"class="dataManageBtn22BtnpPx">添加</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="table-wrap">
            <el-table
                    :data="tableData"
                    style="width:100%;text-align: center;"
                    border
                    cell-class-name="dataManage18px"
                    :header-cell-style="headerCellClassName">
                <el-table-column align="center" v-for="title in tableTitle" :prop="title.prop" :label="title.label"
                                 :show-overflow-tooltip="title.overflowTooltip">
                </el-table-column>
                <template v-if="buttons && buttons.length!==0">
                    <el-table-column
                            class="align-right"
                            width="250px"
                            header-align="center"
                            label="操作"
                            align="center" >
                        <template slot-scope="scope">
                            <el-button v-for="button in buttons"
                                       @click="operate(scope.row,button.href)" :type="button.type"
                                       class="el-button el-button--text dataManageBtn22px">{{button.label}}
                            </el-button>
                        </template>
                    </el-table-column>
                </template>
            </el-table>
            <el-pagination
                    class="dataManage18px"
                    layout="total,prev, pager, next"
                    background
                    @current-change="changePageNum"
                    :current-page="pageNum"
                    :page-size="pageSize"
                    :total="total">
            </el-pagination>
        </div>
        <div>
            <el-dialog :title="title"
                       :visible.sync="showBox"
                       width="40%"
                       @close="closeDialog"
                       append-to-body>
                <el-form ref="form" :model="form" :rules="rules" label-width="120px" >
                    <el-row>
                        <el-col :span="22">
                            <el-form-item label="角色" prop="name">
                                <el-input v-model="form.name" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <!-- <el-col :span="12">
                             <el-form-item label="上级角色" :required="true">
                                 <el-select v-model="form.PID" placeholder="请选择">
                                     <el-option
                                             v-for="item in roleOptions"
                                             :key="item.ID"
                                             :label="item.name"
                                             :value="item.ID">
                                     </el-option>
                                 </el-select>
                             </el-form-item>
                         </el-col>-->
                        <el-col :span="22">

                            <el-form-item label="权限组" prop="authorityGroup">
                                <el-select v-model="form.authorityGroup"
                                           placeholder="请选择"
                                           :loading="loadingGrp"
                                >
                                    <el-option
                                            v-for="item in authorityGrpOptions"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="22">

                            <el-form-item label="权限level" prop="level">
                                <el-select v-model="form.level"
                                           placeholder="请选择"
                                >
                                    <el-option
                                            v-for="item in levelOptions"
                                            :key="item.level"
                                            :label="item.name"
                                            :value="item.level">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="22">
                            <el-form-item label="描述" prop="remark">
                                <el-input v-model="form.remark" clearable type="textarea"></el-input>
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="12">
                             <el-form-item label="排序" :required="true">
                                 <el-input v-model="form.SEQ" clearable></el-input>
                             </el-form-item>
                         </el-col>-->
                    </el-row>


                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="showBox = false" class="dataManageBtn22BtnpPx">取 消</el-button>
                    <el-button type="primary" @click="comfirm" class="dataManageBtn22BtnpPx">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
  import RoleManage from '@/api/dataManages/RoleManage';
  import {mapActions} from 'vuex';

  export default {
    name: 'RoleManage',
    props: {
      FleetId: Number,
      userId: Number,
    },
    data() {
      return {
        name: '',
        rules: {
          name: [
            {required: true, message: '请输入名称', trigger: 'blur'},
            {min: 1, max: 30, message: '长度不能超过30个字符', trigger: 'blur'},
          ], authorityGroup: [
            {required: true, message: '请选择权限组', trigger: 'blur'},
          ],level: [
            {required: true, message: '请选择权限level', trigger: 'blur'},
          ],
          remark: [
            {min: 1, max: 128, message: '长度不能超过128个字符', trigger: 'blur'},
          ]
        },
        tableTitle: [
          {label: '角色', prop: 'name', overflowTooltip: true},
          {label: '描述', prop: 'remark', overflowTooltip: true},
          {label: '权限组', prop: 'authorityGroupName', overflowTooltip: true},
        ],
        tableData: [],
        total: 0,
        type: 0,
        pageNum: 1,
        pageSize: 8,
        buttons: [{label: '编辑', href: 'update'}, {label: '删除', href: 'delete'}],
        showBox: false,
        loadingGrp: false,
        showAdd: true,
        title: '',
        form: {
          id: '',
          name: '',
          remark: '',
          authorityGroup: '',
          level: '',
        },
        roleOptions: [],
        authorityGrpOptions: [],
        levelOptions: [
          {
            level:1,
            name:"1-最低",
          },{
            level:2,
            name:2,
          },{
            level:3,
            name:3,
          },{
            level:4,
            name:4,
          },{
            level:5,
            name:5,
          },{
            level:6,
            name:6,
          },{
            level:7,
            name:7,
          },{
            level:8,
            name:8,
          },{
            level:9,
            name:"9-最高",
          },
        ],
      };
    },
    created() {
      this.changeDmgPage();
    },
    mounted: function() {
      this.query();
      this.getRoleOptions();
    },
    computed: {
      remarkA() {
        return this.form.remark;
      },
    },
    watch: {
      remarkA(val) {
        if (val.length > 100) {
          this.$message.error('描述不能超过100位字符');
          this.form.remark.substring(0, 100);
        }
      },
    },
    methods: {
      querySearch(){
        this.query(1);
        this.pageNum = 1;
      },
      changeDmgPage() {
        let w = window.screen.width;
        let h = window.screen.height;
        if (w == 1920) {
          if (h == 1080) {
          } else {
            this.pageSize = 11;
          }
        }
      },
      //表头样式
      headerCellClassName() {
        return 'font-size:18px;color:#515A6E;padding:10px 0px 10px 0px !important;background:#F5F5F6;border:1px solid #EBEBEB';
      },
      //表格样式
      cellStyleClassName() {
        return 'font-size:13px;text-align:center;color:#606266;padding:5px 0px 5px 0px !important;border:1px solid #EBEBEB';
      },
      closeDialog() {
        console.log("888");
        this.form.name = '';
        this.form.level = '';
        this.form.id = '';
        this.form.authorityGroup = '';
        this.form.remark = '';
        console.log(this.form);

        this.$nextTick(function() {
          this.$refs['form'].resetFields();
        });
      },

      comfirm() {
        if (this.type === 0) {
          this.updateRole();
        } else {
          this.addRole();
        }
      },
      formClear: function() {
        this.form.ID = '';
        this.form.NAME = '';
        this.form.SEQ = '';
        this.form.PID = '';
        this.form.REMARK = '';
      },
      //vuex获取store中方法
      ...mapActions('user', ['chageGlobalUserRoles']),
      query: function(pageNum) {
        var data = {
          name: this.name || '',
          fleetId: this.FleetId,
          pageNum: pageNum || this.pageNum,
          pageSize: this.pageSize,
        };
        RoleManage.getRole(data).then(res => {
          var data = res;
          if (res.success) {
            this.tableData = data.obj.list;
            this.total = data.obj.total;
            this.name = '';
            this.chageGlobalUserRoles(this.$store.getters.userAccount);
          } else {
            this.$message('查询失败');
          }
        }).catch(err => {
          // 异常情况
          console.log(err);
        });
      },
      getRoleOptions: function() {
        RoleManage.getRoleOptions({}).then(res => {
          var data = res;
          if (res.success) {
            this.roleOptions = data.obj.list;
          } else {
            this.$message(res.msg);
          }
        }).catch(err => {
          // 异常情况
          console.log(err);
        });
      },
      getAuthorityGroupOptions(row) {
        this.loadingGrp = true;
        RoleManage.getAuthorityGroup({fleetId: this.FleetId}).then(res => {
          var data = res;
          if (res.success) {
            this.authorityGrpOptions = data.obj.list;
            this.authorityGrpCount = data.obj.total;
            if (this.type === 0) {
              this.showBox = true;
              this.showAdd = false;
              this.title = '编辑';
              this.type = 0;
              this.form.id = row.id;
              this.form.name = row.name;
              this.form.authorityGroup = row.authorityGroup;
              this.form.remark = row.remark;
              this.form.level = row.level;
            } else {
              this.showBox = true;
              this.showAdd = true;
              this.title = '添加角色';
            }
            this.loadingGrp = false;
          } else {
            this.$message('查询权限组失败');
          }
        }).catch(err => {
          // 异常情况
          console.log(err);
        });
      },
      add: function() {
        this.type = 1;
        this.getAuthorityGroupOptions(null);
      },
      addRole: function() {
        var validate = false;
        this.$refs['form'].validate((valid) => {
          if (valid) {
            validate = true;
          } else {
            console.log('error submit!!');
            validate = false;
            return false;
          }
        });
        if (validate === false) {
          return;
        }

        var that = this;
        var data = {
          name: this.form.name,
          remark: this.form.remark,
          fleetId: this.FleetId,
          authorityGroup: this.form.authorityGroup,
          level:this.form.level
        };
        var auditData = {
          dcId: this.$store.getters.userAccount,
          type: 5,
          status: '成功',
          describe: this.$store.getters.userName + '添加角色:' + data.name,
          time: new Date,
          fleetId: this.$store.getters.scsFleetId,
          detailType: 30,
          remark: '',
        };
        RoleManage.addRole(data).then(res => {
          if (res.success) {
            this.GlobalFunc.GlaAddAudit(auditData);
            that.closeBox();
            that.$message.success('添加成功');
            that.query();
            //that.getRoleOptions();

          } else {
            auditData.status = '失败';
            this.GlobalFunc.GlaAddAudit(auditData);
            that.$message('添加失败');
          }
        }).catch(err => {
          // 异常情况
          console.log(err);
          auditData.status = '异常';
          this.GlobalFunc.GlaAddAudit(auditData);

        });
      },
      updateRole: function() {
        var validate = false;
        this.$refs['form'].validate((valid) => {
          if (valid) {
            validate = true;
          } else {
            console.log('error submit!!');
            validate = false;
            return false;
          }
        });
        if (validate === false) {
          return;
        }
        var that = this;
        var data = {
          id: that.form.id,
          name: this.form.name,
          remark: this.form.remark,
          authorityGroup: this.form.authorityGroup,
          level: this.form.level,
        };
        var auditData = {
          dcId: this.$store.getters.userAccount,
          type: 5,
          status: '成功',
          describe: this.$store.getters.userName + '修改角色:' + data.name,
          time: new Date,
          fleetId: this.$store.getters.scsFleetId,
          detailType: 30,
          remark: '',
        };

        RoleManage.updateRole(data).then(res => {
          if (res.success) {
            that.closeBox();
            that.$message.success('编辑成功');
            that.query();
            // that.getRoleOptions();
            this.GlobalFunc.GlaAddAudit(auditData);
          } else {
            that.$message('编辑失败');
            auditData.status = '失败';
            this.GlobalFunc.GlaAddAudit(auditData);
          }
        }).catch(err => {
          // 异常情况
          console.log(err);
          auditData.status = '异常';
          this.GlobalFunc.GlaAddAudit(auditData);
        });
      },
      closeBox: function() {
        // this.formClear();
        this.showBox = false;
      },
      operate(row, href) {
        // that.formClear();
        if (href.indexOf('update') !== -1) {
          this.type = 0;
          this.getAuthorityGroupOptions(row);
        } else {
          var auditData = {
            dcId: this.$store.getters.userAccount,
            type: 5,
            status: '成功',
            describe: this.$store.getters.userName + '删除角色:' + row.name,
            time: new Date,
            fleetId: this.$store.getters.scsFleetId,
            detailType: 30,
            remark: '',
          };

          this.$confirm('是否确定删除', '', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            RoleManage.deleteRole({id: row.id}).then(res => {
              if (res.success) {
                this.GlobalFunc.GlaAddAudit(auditData);
                this.$message.success('删除成功');
                //此时已经实现删除操作，所以total的值需要减1，Math.ceil是向上取整，保证始终大于等于1
                const totalPage = Math.ceil((this.total - 1) / this.pageSize);
                //记住删除最后一条数据时当前码是最后一页
                const tempPageNum = this.pageNum > totalPage ? totalPage : this.pageNum;
                //实现跳转
                this.pageNum = tempPageNum < 1 ? 1 : tempPageNum;
                this.query();
              } else {
                auditData.status = '失败';
                this.GlobalFunc.GlaAddAudit(auditData);
              }
            }).catch(err => {
              // 异常情况
              console.log(err);
              auditData.status = '异常';
              this.GlobalFunc.GlaAddAudit(auditData);
            });
          }).catch(() => {
          });

        }
      },
      changePageNum: function(val) {
        this.pageNum = val;
        this.query();
      },
    },
  };
</script>

<style scoped>
    .el-dialog__body {
        /*height: 30vh;*/
        overflow: auto;
    }

    /deep/ .el-form-item__label {
        font-size: 22px!important;
    }

    /deep/ .el-input__inner {
        font-size: 22px!important;
    }
    /deep/ .el-dialog__title {
        font-size: 22px;
    }
    /deep/ .el-icon-close:before {
        font-size: 25px;
    }

    /*分页修改开始*/
    .el-pagination /deep/ .el-pagination__total {
        font-size: 20px;
        line-height: 60px;
    }

    .el-pagination /deep/ button /deep/ .el-icon .el-icon .el-icon-arrow-left {
        font-size: 50px;
        height: 60px;
        width: 40px;
    }

    /deep/ .el-pager li {
        margin-top: 15px;
        height: 60px;
        width: 60px;
        line-height: 60px;
        font-size: 18px;
    }

    /deep/ .el-pagination.is-background .btn-prev, .el-pager li {
        height: 60px;
        width: 60px;
    }

    /deep/ .el-pagination.is-background .btn-next, .el-pager li {
        height: 60px;
        width: 60px;
    }

    /deep/ .el-pagination .btn-prev .el-icon {
        font-size: 40px;
    }

    /deep/ .el-pagination .btn-next .el-icon {
        font-size: 40px;
    }

    /*分页修改结束*/
    @media (max-width: 1366px) {
        #roleManage .table-wrap {
            height: 800px !important;
            overflow: auto;
        }
    }

    .searchFormBtn {
        margin-left: 5px;
        display: inline-block;
    }
</style>
